//
//  LGLoginVC.m
//  ALS3.0
//
//  Created by guomianxiang on 2017/4/18.
//  Copyright © 2017年 guomianxiang. All rights reserved.
//

#import "LGLoginVC.h"
#import "LGNumberKeyBoard.h"
#import "TouchIDManager.h"
#import "ALSHeader.h"
#import "LoginWindow.h"
#import "LoginViewController.h"
#import "SettingNewPasswordViewController.h"
#import "LGAdminLoginVC.h"
#import "LGShowPasswordVC.h"

//NSString *const AlSFirstRunLogin3_1_1Ver = @"AlSFirstRunLogin3_1_1Ver";

#define k_loginWindow [LoginWindow shareLoginWindw]

#define k_touchIDManager [TouchIDManager sharedTouchIDManager]


@interface LGLoginVC ()<LGNumberKeyBoardDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *errorPasswordlab;
@property (weak, nonatomic) IBOutlet UIButton *forgetPasswordBtn;
@property (weak, nonatomic) IBOutlet UIView *complexPasswordView;
@property (weak, nonatomic) IBOutlet UIView *haveTouchIDView;
@property (weak, nonatomic) IBOutlet UIView *noTouchIDView;
@property (weak, nonatomic) IBOutlet UIView *touchIDView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIButton *passwordLoginBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *keyBoardHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *keyBoardBottom;

@property (assign, nonatomic) BOOL availableTouchID;
@property (assign, nonatomic) BOOL userSetTouchID;

@property (assign, nonatomic) BOOL canUserTouchID;

@property (assign, nonatomic) BOOL isPureDigital;

@property (weak, nonatomic) LGNumberKeyBoard *numberKeyboard;

@property (weak, nonatomic) LGShowPasswordVC *showPasswordVC;

@property (strong, nonatomic) NSMutableString *inputedPassword;

@property (assign, nonatomic) BOOL onceToken;

@end

@implementation LGLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.availableTouchID = k_touchIDManager.canUseTouchID;
    
    self.haveTouchIDView.hidden = !self.availableTouchID;
    self.noTouchIDView.hidden = self.availableTouchID;
    
    self.userSetTouchID = NSUDIsTouchIDLogin;
//    [[NSUserDefaults standardUserDefaults]boolForKey:ALSTouchIDLogin]
    
    self.canUserTouchID = [k_touchIDManager canUseTouchIDWithError:nil];
    
    self.isPureDigital = [self pure6Digital];
    
    self.onceToken = YES;
    
    self.textField.tintColor = kALSHightBlueColor;

}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
//    NSLog(@"presentationController:%@",self.presentationController);

}

- (void)viewWillLayoutSubviews {
    // 键盘高度220  logo高度100 touchid高度90 passwordView高度 20

}

- (void)viewDidAppear:(BOOL)animated {
    [self getChildVC];
    
    if (self.onceToken) {
        self.onceToken = NO;
        [self loginFlowAndShowPresention:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - founcation

- (void)loginFlowAndShowPresention:(BOOL)presentation {
    if (!self.userSetTouchID) {
        if (presentation) [k_loginWindow showSetTouchIDLoginHUD];
    }
    else if (!self.canUserTouchID) {
        if (presentation) [k_loginWindow showTouchIDLockHUD];
    }
    else {
        [self touchIDLogin];
        return;
    }
    
    [self passwordLoginFlow];
    
}

- (void)passwordLoginFlow {
    if ([self pure6Digital]) {
        [self pureDigitalLogin];
        return;
    }
    [self complexPasswordLogin];
}

- (void)touchIDLogin {
    [self.view endEditing:YES];
    __weak typeof(self)weakSelf = self;
//    [[NSUserDefaults standardUserDefaults]boolForKey:ALSStartTouchID]
    if (!NSUDIsStartTouchID) {
        [NSUD setBool:YES forKey:ALSStartTouchID];
        return;
    }

    [self.passwordLoginBtn setTitle:@"使用密码登录" forState:(UIControlStateNormal)];
    
    void(^touchIDLoginBlock)() = ^{
        [k_touchIDManager touchIDLoginSuccessHandler:^{
            
            [weakSelf loginSuccess];
            
        } failHandler:^(NSError * _Nullable error) {
            
            NSLog(@"--%@",error.localizedDescription);
            switch (error.code) {
                    
                case LAErrorUserFallback:
                    [weakSelf passwordLoginFlow];
                    break;
                case LAErrorTouchIDLockout:
                    //指纹被锁定
                    [k_loginWindow showTouchIDLockHUD];
                    
                    [weakSelf passwordLoginFlow];
                    
                    break;
                case LAErrorAuthenticationFailed:
                    //3次验证指纹失败
                    [k_loginWindow showTouchIDAuthenticationFailedHUD];
                    break;
                default:
                    break;
                    
            }
            
        }];
    };
    
    
    if (self.keyBoardBottom.constant == 0 || self.complexPasswordView.alpha > 0.5) {
        
        self.keyBoardBottom.constant = -220;
        
        [UIView animateWithDuration:0.3 animations:^{
            [weakSelf.view layoutIfNeeded];
            
            weakSelf.touchIDView.alpha = 0.99;
            weakSelf.passwordView.alpha = 0.01;
            weakSelf.complexPasswordView.alpha = 0.01;
        } completion:^(BOOL finished) {
            touchIDLoginBlock();
        }];
    }else {

        touchIDLoginBlock();
    }
}

- (void)pureDigitalLogin {
    [self.view endEditing:YES];
    [self.passwordLoginBtn setTitle:@"使用指纹登录" forState:(UIControlStateNormal)];
    
    self.keyBoardBottom.constant = 0;
    
    self.inputedPassword = [NSMutableString string];
    [self.showPasswordVC removeAllCirCle];
    
    __weak typeof(self)weakSelf = self;

    [UIView animateWithDuration:0.3 animations:^{

        [self.view layoutSubviews];
        
        weakSelf.touchIDView.alpha = 0.01;
        weakSelf.passwordView.alpha = 0.99;
        weakSelf.complexPasswordView.alpha = 0.01;
    }];
    
}

- (void)complexPasswordLogin{
    
    [self.passwordLoginBtn setTitle:@"使用指纹登录" forState:(UIControlStateNormal)];
    
//    self.keyBoardBottom.constant = -220;

    __weak typeof(self)weakSelf = self;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [self.view layoutSubviews];
        
        weakSelf.touchIDView.alpha = 0.01;
        weakSelf.passwordView.alpha = 0.01;
        weakSelf.complexPasswordView.alpha = 0.99;
        
    }];
    
    [self.textField becomeFirstResponder];
    
}

- (void)getChildVC {
    for (NSInteger i=0; i<self.childViewControllers.count; i++) {
        if ([self.childViewControllers[i] isKindOfClass:[LGNumberKeyBoard class]]) {
            self.numberKeyboard = self.childViewControllers[i];
            self.numberKeyboard.delegate = self;
        }
        if ([self.childViewControllers[i] isKindOfClass:[LGShowPasswordVC class]]) {
            self.showPasswordVC = self.childViewControllers[i];
        }
    }
}

- (BOOL)pure6Digital {
    NSString *password = NSUDStrALSPassword;
//    [[NSUserDefaults standardUserDefaults]objectForKey:ALSPassword]
    NSScanner *scan = [NSScanner scannerWithString:password];
    int val;
    if ([scan scanInt:&val] && [scan isAtEnd] && password.length == 6) return YES;
    
    return NO;
}

- (IBAction)touchIDBtnClick:(UIButton *)sender {
    [self touchIDLogin];
}

- (IBAction)adminLoginBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    
    [self performSegueWithIdentifier:NSStringFromClass([LGAdminLoginVC class]) sender:nil];
}

- (IBAction)passwordLoginBtnClick:(UIButton *)sender {
    
    if (self.keyBoardBottom.constant == 0 || self.complexPasswordView.alpha > 0.5) {
        [self loginFlowAndShowPresention:YES];
    }else {

        [self passwordLoginFlow];
    }
    
    return;
    
}

- (IBAction)loginBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    
    if ([self validPassword]) {
        [self loginSuccess];
    }
   
}

- (IBAction)forgetPasswordBtn:(UIButton *)sender {
    //    无指纹识别  指纹识别被锁住  可以指纹识别
//#warning 无指纹识别  指纹识别被锁住  可以指纹识别
    [self.view endEditing:YES];
    if (self.availableTouchID) {
        [self performSegueWithIdentifier:NSStringFromClass([SettingNewPasswordViewController class]) sender:@1];
    }else {
        [k_loginWindow showMessageAdminHUD];
    }
    
}

- (void)loginSuccess {
    
    __weak typeof(self)weakSelf = self;
    NSString *Ver = [[[NSBundle mainBundle]infoDictionary] valueForKey:@"CFBundleShortVersionString"];
    if (!self.isPureDigital && ![NSUD boolForKey:Ver]) {
        
        [NSUD setBool:YES forKey:Ver];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录成功" message:@"推荐你使用数字密码，使用方便且同样可以保证安全" preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *setNewPassword = [UIAlertAction actionWithTitle:@"去设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf performSegueWithIdentifier:NSStringFromClass([SettingNewPasswordViewController class]) sender:@0];
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [k_loginWindow dismiss];
        }];
        
        [alert addAction:cancel];
        [alert addAction:setNewPassword];
        [weakSelf presentViewController:alert animated:YES completion:nil];

    }else {
        [k_loginWindow dismiss];
    }
    
}

/**
 验证密码正确性
 
 @return default
 */
- (BOOL)validPassword {
    if ([self.textField.text isEqualToString:NSUDStrALSPassword]) {
        self.errorPasswordlab.hidden = NO;
        return YES;
        
    }
    self.errorPasswordlab.hidden = NO;
    
    return NO;
    
}
#pragma mark - LGNumberKeyBoardDelegate

- (void)numberKeyBoardCommitActionType:(LGNumberKeyBoardActionType)actionType andNumber:(NSInteger)number {
    switch (actionType) {
        case LGNumberKeyBoardActionCancel:
        {
            if (self.inputedPassword.length == 0) return;
            [self.showPasswordVC removeLastCircle];
            [self.inputedPassword deleteCharactersInRange:NSMakeRange(self.inputedPassword.length - 1, 1)];
        }
            break;
        case LGNumberKeyBoardActionForget:
        {
            [self forgetPasswordBtn:nil];
        }
            break;
            
        case LGNumberKeyBoardActionNumber:
        {
            [self.showPasswordVC addCircle];

            [self.inputedPassword appendString:[NSString stringWithFormat:@"%li",number]];
        }
            break;
        default:
            break;
    }
    
    if (self.inputedPassword.length != 6) return;

    if ([self.inputedPassword isEqualToString:NSUDStrALSPassword]) {
        
        [self loginSuccess];
    }else {
//        NSLog(@"-------");
        self.inputedPassword  = [NSMutableString string];
        [self.showPasswordVC startErrorAnimalAndRemoveAllCircle];
    }
        
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:NSStringFromClass([SettingNewPasswordViewController class])]) {
        
        SettingNewPasswordViewController *vc = segue.destinationViewController;
        
        NSNumber *number = (NSNumber *)sender;
        
        vc.needValid = [number boolValue];

    }
    
    
}

#pragma mark - other
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
    [self validPassword];
}

@end

//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passwordViewTop;

//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTop;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *touchIDTop;


//- (void)loginFlow {
//    if (self.userSetTouchID && self.canUserTouchID) {
//        [self touchIDLogin];
//        return;
//    }
//    if ([self pureDigital]) {
//        [self pureDigitalLogin];
//        return;
//    }
//    [self complexPasswordLogin];
//}
//
